<script lang="ts" setup>
import { QTable, type TableColums } from '@meetjs/element-plus-kit'
import { ref, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getChangeListApi, batchApprovalChangeApi, batchApprovalAllPendingApi } from '@/api/athlete/change/index'
import { ChangeType, type ChangeQueryParams, type ProjectChangeInfo } from '@/api/athlete/change/types'
import { ManagementStatus } from '@/api/athlete/types'
import { useDict } from '@/composables/useDict'
import { useProjectChangeListStore } from '@/store/athlete/projectChangeList'
import { ATHLETE_DICT } from '@/constants/dictKeys'

const { init: initCommonDicts, getDictLabel, getTrainOrgLabel, getRegisterOrgLabel } = useDict([ATHLETE_DICT.PROJECT])

// 表格加载状态
const loading = ref(false)

// 路由实例
const router = useRouter()

// 项目变更列表Store
const projectChangeStore = useProjectChangeListStore()

// 状态筛选 - 使用统一的 ManagementStatus 枚举
const selectedStatus = ref(ManagementStatus.PENDING) // 默认选中待处理
const statusOptions = [
	{
		label: '待处理',
		value: ManagementStatus.PENDING
	},
	{
		label: '已核准',
		value: ManagementStatus.APPROVED
	},
	{
		label: '已驳回',
		value: ManagementStatus.REJECTED
	},
	{
		label: '全部',
		value: ManagementStatus.ALL
	}
]

// 分页配置
const page = ref({
	currentPage: 1,
	pageSize: 10,
	total: 0
})

// 表格数据使用ProjectChangeInfo类型
const tableData = ref<ProjectChangeInfo[]>([])

// 表格选中状态
const selectedRows = ref<ProjectChangeInfo[]>([])

// 弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogType = ref<'approve' | 'reject'>('approve')
const dialogForm = ref({
	opinion: '' // 核准意见或驳回原因
})

// 表格列配置 - 按照需求定义列结构
const getColumns = computed<TableColums[]>(() => {
	const baseColumns: TableColums[] = [
		{
			type: 'selection',
			width: 55,
			align: 'center'
		},
		{
			label: '运动员姓名',
			prop: 'athleteName',
			width: 160,
			align: 'left'
		},
		{
			label: '性别',
			prop: 'sexLabel',
			width: 80,
			align: 'center'
		},
		{
			label: '身份证号',
			prop: 'idNumber',
			width: 120,
			align: 'center'
		},
		{
			label: '注册证号',
			prop: 'registerNumber',
			width: 120,
			align: 'center'
		},
		{
			label: '变更前项目信息',
			prop: 'changeBeforeProjectLabel',
			width: 200,
			align: 'center'
		},
		{
			label: '变更后项目信息',
			prop: 'changeAfterProjectLabel',
			width: 200,
			align: 'center'
		},
		{
			label: '在训单位',
			prop: 'trainOrgLabel',
			width: 160,
			align: 'center'
		},
		{
			label: '注册单位',
			prop: 'trainOrgLabel',
			width: 160,
			align: 'center'
		},
		{
			label: '注册年度',
			prop: 'registerYear',
			width: 100,
			align: 'center'
		},
		{
			label: '首次注册年度',
			prop: 'firstRegisterYear',
			width: 120,
			align: 'center'
		}
	]

	// 仅在【全部】和【已驳回】状态下显示驳回原因
	if (selectedStatus.value === ManagementStatus.ALL || selectedStatus.value === ManagementStatus.REJECTED) {
		baseColumns.push({
			label: '驳回原因',
			prop: 'rejectReason',
			minWidth: 140,
			align: 'center'
		})
	}

	// 操作列
	baseColumns.push({
		prop: 'action',
		fixed: 'right',
		label: '操作',
		align: 'center',
		minWidth: 160
	})

	return baseColumns
})

// 获取表格数据 - 通过Store缓存ID列表
const getTableData = async () => {
	try {
		loading.value = true

		// 构建查询参数
		const queryParams: ChangeQueryParams = {
			pageNum: page.value.currentPage,
			pageSize: page.value.pageSize,
			changeType: ChangeType.PROJECT_CHANGE // 项目变更
		}

		// 根据选中状态动态设置approvalStatus
		if (selectedStatus.value !== ManagementStatus.ALL) {
			queryParams.approvalStatus = selectedStatus.value
		}

		//  同步分页信息到Store
		projectChangeStore.setCurrentPage(page.value.currentPage)
		projectChangeStore.setPageSize(page.value.pageSize)

		//  通过Store加载列表数据（存储完整数据）
		const list = await projectChangeStore.loadList(queryParams)

		//  直接使用Store中的完整数据，添加显示用的计算字段
		tableData.value = list.map(row => ({
			...row,
			// 性别标签
			sexLabel: row.sex === 0 ? '男' : '女',
			// 变更前项目信息
			changeBeforeProjectLabel: getDictLabel(ATHLETE_DICT.PROJECT, row.changeBefore),
			// 变更后项目信息
			changeAfterProjectLabel: getDictLabel(ATHLETE_DICT.PROJECT, row.changeAfter),
			// 注册单位
			registerOrgLabel: getRegisterOrgLabel(row.registerOrgId),
			// 在训单位
			trainOrgLabel: getTrainOrgLabel(row.trainOrgId)
		})) as ProjectChangeInfo[]

		page.value.total = projectChangeStore.pagination.total

		console.log('项目变更表格数据:', tableData.value)
		console.log('缓存的列表数据:', projectChangeStore.list)
	} catch (error) {
		console.error('加载项目变更数据失败:', error)
		ElMessage.error('加载项目变更数据失败，请重试')
	} finally {
		loading.value = false
	}
}

// 监听状态改变，重新加载数据
watch(selectedStatus, () => {
	page.value.currentPage = 1
	getTableData()
})

// 表格选择改变处理
const handleSelectionChange = (selection: ProjectChangeInfo[]) => {
	selectedRows.value = selection
}

// 批量核准
const handleBatchApprove = () => {
	if (selectedRows.value.length === 0) {
		ElMessage.warning('请选择要核准的变更申请')
		return
	}
	openDialog('approve', `批量核准（${selectedRows.value.length}件）`)
}

// 一键核准
const handleOneClickApprove = () => {
	if (tableData.value.length === 0) {
		ElMessage.warning('当前没有可核准的变更申请')
		return
	}
	openDialog('approve', `一键核准（${tableData.value.length}件）`)
}

// 批量驳回
const handleBatchReject = () => {
	if (selectedRows.value.length === 0) {
		ElMessage.warning('请选择要驳回的变更申请')
		return
	}
	openDialog('reject', `批量驳回（${selectedRows.value.length}件）`)
}

// 打开弹窗
const openDialog = (type: 'approve' | 'reject', title: string) => {
	dialogType.value = type
	dialogTitle.value = title
	dialogForm.value.opinion = ''
	dialogVisible.value = true
}

// 确认弹窗操作
const handleDialogConfirm = async () => {
	if (!dialogForm.value.opinion.trim()) {
		ElMessage.warning(dialogType.value === 'approve' ? '请输入核准意见' : '请输入驳回原因')
		return
	}

	try {
		// 构建审批参数
		const isOneClick = selectedRows.value.length === tableData.value.length
		const approvalParams: any = {
			approvalStatus: dialogType.value === 'approve' ? ManagementStatus.APPROVED : ManagementStatus.REJECTED
		}

		// 添加审批意见或驳回原因
		if (dialogType.value === 'approve') {
			approvalParams.approvalOpinion = dialogForm.value.opinion
		} else {
			approvalParams.rejectReason = dialogForm.value.opinion
		}

		// 调用对应的接口
		if (isOneClick) {
			// 一键操作
			await batchApprovalAllPendingApi(approvalParams)
		} else {
			// 批量操作
			const ids = selectedRows.value.map(row => row.id!)
			await batchApprovalChangeApi({
				...approvalParams,
				ids
			})
		}

		ElMessage.success(dialogType.value === 'approve' ? '核准成功' : '驳回成功')
		dialogVisible.value = false
		getTableData() // 刷新数据
	} catch (error) {
		console.error('审批失败:', error)
		ElMessage.error('审批失败，请重试')
	}
}

// 单个操作 - 核准
const handleRowApprove = (row: ProjectChangeInfo) => {
	selectedRows.value = [row]
	openDialog('approve', `核准项目变更: ${row.athleteName}`)
}

// 单个操作 - 驳回
const handleRowReject = (row: ProjectChangeInfo) => {
	selectedRows.value = [row]
	openDialog('reject', `驳回项目变更: ${row.athleteName}`)
}

// 单个操作 - 查看
const handleRowView = (row: ProjectChangeInfo) => {
	// 跳转到运动员详情页面
	if (row.infoId) {
		//  设置当前运动员到Store
		projectChangeStore.setCurrentById(row.infoId)

		//  使用query参数标识来源，禁用导航功能
		router.push({
			path: '/athleteFirst/detail',
			query: {
				id: row.infoId,
				from: 'projectChange',
				disableNav: '1' //  禁用上下翻页导航
			}
		})
	} else {
		ElMessage.error('无法获取运动员ID')
		console.error('运动员数据缺少 infoId 字段:', row)
	}
}

// 组件挂载时加载数据
onMounted(async () => {
	await initCommonDicts()
	await getTableData()
})
</script>

<template>
	<div class="flex flex-1 min-h-0">
		<!-- 左侧表格区 -->
		<div class="flex-1 flex flex-col min-w-0 table-page-box p-5">
			<!-- 状态筛选和操作按钮 -->
			<div class="flex items-center justify-between mb-4">
				<!-- 左侧单选按钮组 -->
				<el-radio-group
					v-model="selectedStatus"
					class="flex gap-6"
				>
					<el-radio
						v-for="option in statusOptions"
						:key="option.value"
						:value="option.value"
						class="mr-0!"
					>
						{{ option.label }}
					</el-radio>
				</el-radio-group>

				<!-- 右侧操作按钮组 - 根据状态动态显示 -->
				<div class="flex">
					<!-- 【待处理】状态的操作按钮 -->
					<template v-if="selectedStatus === ManagementStatus.PENDING">
						<el-button
							type="primary"
							size="default"
							@click="handleOneClickApprove"
						>
							一键核准
						</el-button>
						<el-button
							type="primary"
							size="default"
							@click="handleBatchApprove"
						>
							批量核准
						</el-button>
						<el-button
							type="danger"
							size="default"
							@click="handleBatchReject"
						>
							批量驳回
						</el-button>
					</template>
				</div>
			</div>
			<div class="table-box flex-1 p-0!">
				<!-- QTable -->
				<QTable
					:data="tableData"
					:columns="getColumns"
					:loading="loading"
					:page="page"
					@pageChange="getTableData"
					@selectionChange="handleSelectionChange"
				>
					<!-- 操作列 - 根据状态动态显示按钮 -->
					<template #action="{ row }">
						<div class="flex gap-2 justify-center">
							<!-- 【待处理】操作 -->
							<template v-if="selectedStatus === ManagementStatus.PENDING">
								<el-button
									type="primary"
									link
									size="small"
									@click="handleRowApprove(row)"
								>
									核准
								</el-button>
								<el-button
									type="primary"
									link
									size="small"
									@click="handleRowView(row)"
								>
									查看
								</el-button>
								<el-button
									type="danger"
									link
									size="small"
									@click="handleRowReject(row)"
								>
									驳回
								</el-button>
							</template>

							<!-- 其他状态只有查看 -->
							<template v-else>
								<el-button
									type="primary"
									link
									size="small"
									@click="handleRowView(row)"
								>
									查看
								</el-button>
							</template>
						</div>
					</template>
				</QTable>
			</div>
		</div>
		<!-- 核准/驳回弹窗 -->
		<el-dialog
			v-model="dialogVisible"
			:title="dialogTitle"
			width="500px"
			@close="dialogVisible = false"
		>
			<el-form
				:model="dialogForm"
				label-width="120px"
				label-position="top"
			>
				<el-form-item
					:label="dialogType === 'approve' ? '核准意见' : '驳回原因'"
					required
				>
					<el-input
						v-model="dialogForm.opinion"
						type="textarea"
						:placeholder="dialogType === 'approve' ? '请输入核准意见' : '请输入驳回原因'"
						:rows="4"
						maxlength="500"
						show-word-limit
					/>
				</el-form-item>
			</el-form>

			<template #footer>
				<div class="flex justify-end gap-3">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button
						type="primary"
						@click="handleDialogConfirm"
					>
						确定
					</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
